<template>
  <div id="printBarcodeQuery">
    <Breadcrumb content="条码信息查询" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="16">
          <vxe-form :data="newForm" class-name="padding-sm width-100-percentage" title-width="80px">
            <vxe-form-item title="病历号" field="patNo" class-name="width-100-percentage" :item-render="{}">
              <template #default="{ data }">
                <vxe-input v-model="data.patNo" placeholder="病历号" class-name="width-100-percentage" clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="病历号前缀" :item-render="{}" field="beforePatNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.beforePatNo" placeholder="病历号前缀" class-name="width-100-percentage" clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请号" :item-render="{}" field="reqNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.reqNo" placeholder="申请号" class-name="width-100-percentage" clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="床号" :item-render="{}" field="bedNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.bedNo" placeholder="床号" class-name="width-100-percentage" clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <!--            <vxe-form-item title="病人来源" field="patTypeName" :item-render="{}" class-name="width-100-percentage">-->
            <!--              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[-->
            <!--                { title: '编码', props: 'code' }, //列标题-->
            <!--                { title: '名称', props: 'name' }-->
            <!--              ]" :title="'点击选择病人来源'" :searchParam="{ code: 'PATTYPE' }" @selectDataRow="SelectRowClick" :inputWidth="'100%'" v-model="newForm.patTypeName" :placeholder="'选择病人来源'" @clearValue="clearPatTypeName" />-->
            <!--              &lt;!&ndash; </template> &ndash;&gt;-->
            <!--            </vxe-form-item>-->

            <vxe-form-item title="病人来源" field="patTypeName" :item-render="{}" class-name="width-100-percentage no-edit">
              <SelectDataCheckedList ref="patTypeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :column="[
                                                { field: 'code', title: '编码' }, //列标题
                                                { field: 'name', title: '名称' }
                                              ]" :searchParam="{ code: 'PATTYPE' }" :isPage="false" @SelectCellClick="(e) => {
                selectPatTypeNameRow(e, rowIndex);
              }" :clickRowId="typeIds" :showField="'name'" :inputWidth="'100%'">
              </SelectDataCheckedList>
            </vxe-form-item>

            <vxe-form-item title="科室" :item-render="{}" field="deptNa" class-name="width-100-percentage">
              <!-- <template #default="{ row }">
                                <span>{{ formatItemNameByIds(row) }}</span>
                            </template> -->
              <!-- <template #edit="{ rowIndex }"> -->
              <SelectDataCheckedList ref="deptDropSelectRef" :url="'/api/sys/getDepartAuthorizementList'" :column="[
                { field: 'code', title: '科室编码' }, //列标题
                { field: 'name', title: '科室名称' }
              ]" :searchParam="{ orgId , username:store.userInfo.username,deptNoList}" :isPage="false" @SelectCellClick="(e) => {
                selectRow(e, rowIndex);
              }
                " :clickRowId="deptIds" :showField="'name'" :inputWidth="'100%'" v-if="!IsEmpty(barObjKey)">
              </SelectDataCheckedList>

              <SelectDataCheckedList ref="deptDropSelectRef" :url="'/api/sys/getDepartmentList'" :column="[
                { field: 'code', title: '科室编码' }, //列标题
                { field: 'name', title: '科室名称' }
              ]" :searchParam="{ orgId }" :isPage="false" @SelectCellClick="(e) => {
                selectRow(e, rowIndex);
              }
                " :clickRowId="deptIds" :showField="'name'" :inputWidth="'100%'" v-else>
              </SelectDataCheckedList>
            </vxe-form-item>

            <vxe-form-item title="姓名" :item-render="{}" field="patNa" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.patNa" placeholder="姓名" class-name="width-100-percentage" clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="身份证号" :item-render="{}" field="IDNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input ref="refInputIDNo" v-model="data.IDNo" placeholder="身份证号" class-name="width-100-percentage" @keyup.enter.native="IDNoValueChangeEnter" clearable />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[始]" :item-render="{}" field="reqDateS" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[始]" v-model="data.reqDateS" type="datetime" class-name="width-100-percentage" transfer />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[止]" :item-render="{}" field="reqDateE" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[止]" v-model="data.reqDateE" type="datetime" class-name="width-100-percentage" transfer />
              </template>
            </vxe-form-item>
          </vxe-form>
        </Pane>
        <Pane size="84">
          <Splitpanes horizontal>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #buttons>
                    <vxe-input v-model="newForm.searchValue" placeholder="请输入关键字" clearable @clear="findPrintBarcodeSpecList()" @keyup="keyupEnter"></vxe-input>
                    <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-search" class-name="text-blue" content="查询" @click="findPrintBarcodeSpecList"></vxe-button>
                    <!-- <vxe-button type="text" icon="vxe-icon-search" class-name="text-blue" content="查询"
                                            @click="findPrintBarcodeSpecList"></vxe-button> -->
                    <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-paste" class-name="text-green" content="读卡" @click="IdNoFocus"></vxe-button>
                    <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-print" class-name="text-orange" content="重打条码" @click="printManyStep1('printBarcodeQueryTable')"></vxe-button>
                    <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-print" class-name="text-orange" content="导出" @click="exportExcel"></vxe-button>
                    <!-- <vxe-button type="text" icon="vxe-icon-print" class-name="text-orange" content="测试插入申请项目" @click="testInsertAppItem"></vxe-button> -->
                    <!-- <vxe-button type="text" icon="vxe-icon-maximize" class-name="text-olive" content="重新打印" @click="findPrintBarcodeSpecList"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-delete-fill" class-name="text-red" content="删除" @click="findPrintBarcodeSpecList"></vxe-button> -->
                    <vxe-button type="text" class="button-red margin-left-sm" icon="vxe-icon-delete-fill" content="作废条码" @click="cancelSpec"></vxe-button>
                    <vxe-checkbox v-model="isPrintZYD" class="margin-left-xs" :checked-value="'1'" :unchecked-value="'0'">打印回执单</vxe-checkbox>
                  </template>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom" @dblclick="setCurComputerCheckedisPrintZYD">待重打印条码申请</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodeQueryTable" :style="{ height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px)' }">
                <vxe-table ref="printBarcodeQueryTable" v-loading="loading" border height="auto" :menu-config="tableMenuTop" @menu-click="contextMenuClickEvent" :cell-style="cellStyle" :cell-class-name="cellClassName" :data="printBarcodeQueryList" @checkbox-change="checkboxStateChange" @cell-click="printBarcodeQueryRowClick" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }" resizable show-overflow>
                  <vxe-column type="checkbox" width="26"></vxe-column>
                  <vxe-column type="seq" title="序号" width="30"></vxe-column>
                  <vxe-column field="isCatch" title="" width="16px" align="center">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                    </template>
                    <template #default="{ row }">
                      <span style="color: white">{{ row.isCatch ? 'x' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column width="16" field="isEmergency" title="急诊" align="center">
                    <template #header>
                      <span style="font-size: 0.85rem; font-weight: 550">急</span>
                    </template>
                    <template #default="{ row }">
                      <span>{{ row.isEmergency ? '' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="stateNa" title="标本状态" width="100"></vxe-column>
                  <vxe-column field="reqNo" title="条码号" width="160px"></vxe-column>
                  <vxe-column field="rptGroup" title="报告单元" width="100px"></vxe-column>
                  <vxe-column field="sampleda" title="检验日期" width="120px"></vxe-column>
                  <vxe-column field="sampleNo" title="标本号" width="80px"></vxe-column>
                  <vxe-column field="patTypeNa" title="病人类型" width="80px"></vxe-column>
                  <vxe-column field="patNa" title="姓名" width="80px"></vxe-column>
                  <vxe-column field="sexNa" title="性别" width="30px"></vxe-column>
                  <vxe-column field="ageStr" title="年龄" width="60px"></vxe-column>
                  <vxe-column field="reqDeptNa" title="科室" width="80px"></vxe-column>
                  <vxe-column field="bedNo" title="床号" width="80px"></vxe-column>
                  <vxe-column field="reqPurpose" title="申请项目名称" width="280"></vxe-column>
                  <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
                  <vxe-column field="reqDoctorNa" title="开单医生" width="80"></vxe-column>
                  <vxe-column field="idNo" title="身份证号" width="100px"></vxe-column>
                  <vxe-column field="sampleType" title="条码类别代码" width="100"></vxe-column>
                  <vxe-column field="sampleTypeNa" title="条码类别名称" width="100"></vxe-column>
                  <vxe-column field="reqTime" title="申请时间" width="120"></vxe-column>
                  <vxe-column field="printTime" title="打印时间" width="120"></vxe-column>
                  <vxe-column field="printerNa" title="打印人" width="60"></vxe-column>
                  <!-- <vxe-column field="amount" title="数量" width="60"></vxe-column>
                  <vxe-column field="price" title="金额" width="60"></vxe-column> -->
                  <vxe-column field="samplingDoctorNa" title="采集人" width="60"></vxe-column>
                  <vxe-column field="samplingTime" title="采集时间" width="120"></vxe-column>
                  <vxe-column field="signTime" title="接收时间" width="120"></vxe-column>
                  <vxe-column field="catchMessage" title="异常提示" min-width="100"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom">申请项目信息</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodeQueryTable" :style="{
                height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px - 8px)'
              }">
                <vxe-table ref="reqDetailTable" v-loading="afterloading" border height="auto" align="left" :menu-config="tableMenuBottom" :cell-style="cellStyle" :checkbox-config="{ range: true }" :cell-class-name="cellClassName" :data="afterPrintBarcodeSpecList" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }" resizable show-overflow :scroll-y="{ enabled: true, gt: 50 }">
                  <vxe-column type="checkbox" width="26" fixed="left"></vxe-column>
                  <vxe-column field="reqNo" title="条码号" width="95px"></vxe-column>
                  <vxe-column field="feeCode" title="收费项目代号" width="90"></vxe-column>
                  <vxe-column field="feeName" title="收费项目名称" min-width="120"></vxe-column>
                  <vxe-column field="amount" title="数量" width="30px" align="right"></vxe-column>
                  <vxe-column field="price" title="单价" width="50px" align="right"></vxe-column>
                  <vxe-column field="costs" title="金额" width="80px" align="right"></vxe-column>
                  <vxe-column field="groupCode" title="申请项目组合编码"></vxe-column>
                  <vxe-column field="groupName" title="申请项目组合名称"></vxe-column>
                  <!-- <vxe-column field="costs" title="金额" width="80px"></vxe-column> -->
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    <!-- 静默打印-指引单 -->
    <QuietPrint ref="quietPrintZydRef" :printParams="printParamsZydObj" />
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, inject } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty, formatDateTime, splitArray } from '@/utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance, List } from 'vxe-table';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes'; //比例拖拉条
import SelectDataList from '@/components/SelectDataList.vue';
import { AppStore } from '../../../stores/store';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import QuietPrint from '@/components/QuietPrint.vue';
import XEClipboard from 'xe-clipboard';
import { LocGet, LocPost } from '@/utils/LocRequestHelper';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
// 双击配置本机电脑默认病人来源1
let showDefaultVisitTypeModal = false;
let isPrintZYD = ref('0'); //是否打印指引单
let isChildren = false;
let loading = ref(false);
let afterloading = ref(false);
let afterPrintBarcodeSpecList: any = reactive([]); //已打印列表
let printBarcodeQueryList: any = reactive([]); //待打印列表
const deptDropSelectRef = ref(null); /** */
let currentPrintBarcode = reactive({}) as any; //当前选中行
let currentRowIndex = ref(0);
let printParamsObj = ref(null); //打印参数
let printParamsZydObj = ref(null); //指引单参数
let deptIds = ref('');
let barObjKey = ref('');
let typeIds = ref('');
let reportId = ref('');
let orgId = ref(null);

const printBarcodeQueryTable = ref(null); //表格ref标记
const patTypeSelectRef = ref(null); /**来源下拉框 */
let deptNoList = reactive([]);
const newForm = reactive({
  searchValue: '',
  patNo: '',
  beforePatNo: '',
  reqNo: '',
  bedNo: '',
  patType: [] as any,
  patTypeName: '',
  deptNo: [] as any,
  deptNa: '',
  patNa: '',
  IDNo: '',
  reqDateS: formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00'),
  reqDateE: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59')
});

let tableMenuTop = reactive({
  className: 'my-menus',
  body: {
    options: [[{ code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }], [{ code: 'cancel', name: '作废条码', prefixIcon: 'vxe-icon-delete', className: 'my-copy-item' }]]
  }
});
let tableMenuBottom = reactive({
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' },
        {
          code: 'print',
          name: '打印选中',
          prefixIcon: 'vxe-icon-print',
          className: 'my-copy-item'
        },
        {
          code: 'refresh',
          name: '刷新列表',
          prefixIcon: 'vxe-icon-refresh',
          className: 'my-copy-item'
        }
      ]
    ]
  }
});

// 页面加载时更新报告单元/字典
onMounted(async () => {
  //#region  病人来源
  try {
    const url1 = (window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + `/api/LocalParams/get-local-setting?key=${'specPrintVisitType'}`;
    const r = await LocPost(url1);
    deptIds.value = r;
  } catch (err) {}

  try {
    let BarObjKey = sessionStorage.getItem('QueryObjKey');
    if (!IsEmpty(BarObjKey)) {
      barObjKey.value = BarObjKey;
    }
  } catch (error) {}
  //#endregion
  try {
    let BarCodePrtDeps = sessionStorage.getItem('BarCodePrtDeps');
    if (!IsEmpty(BarCodePrtDeps)) {
      deptIds.value = BarCodePrtDeps;
      loadCacheDeps(BarCodePrtDeps);

      /**填充组织机构 */
      if (BarCodePrtDeps.indexOf(',') > -1) {
        const ass = BarCodePrtDeps.split(',');
        newForm.deptNo.length = 0;
        Object.assign(newForm.deptNo, ass);
        deptNoList.length = 0;
        Object.assign(deptNoList, ass);
      } else {
        Object.assign(newForm.deptNo, [BarCodePrtDeps]);
        deptNoList.length = 0;
        Object.assign(deptNoList, [BarCodePrtDeps]);
      }
    }
  } catch (error) {}
  //#endregion

  //#region  病人来源
  try {
    const locPatType = sessionStorage.getItem('QueryPatType');
    if (!IsEmpty(locPatType)) {
      typeIds.value = locPatType;
      loadCachePatType(locPatType);

      /**填充来源 */
      if (locPatType.indexOf(',') > -1) {
        const ass = locPatType.split(',');
        newForm.patType.length = 0;
        Object.assign(newForm.patType, ass);
      } else {
        Object.assign(newForm.patType, [locPatType]);
      }
    }
    // if (IsEmpty(newForm.patType)) {
    //   newForm.patType = IsEmpty(locPatType) ? '' : locPatType;
    // }
    // if (IsEmpty(newForm.patTypeName) && !IsEmpty(newForm.patType)) {
    //   switch (newForm.patType) {
    //     case '1':
    //       newForm.patTypeName = '门诊';
    //       break;
    //     case '2':
    //       newForm.patTypeName = '急诊';
    //       break;
    //     case '3':
    //       newForm.patTypeName = '住院';
    //       break;
    //     case '4':
    //       newForm.patTypeName = '体检';
    //       break;
    //     default:
    //       break;
    //   }
    // }
  } catch (error) {
    //todo
  }
  //#endregion

  orgId = store.userInfo.orgId;
  getReportId();

  //#region  打印回执单设置
  try {
    const flag = localStorage.getItem('isPrintZYD');
    if (flag) {
      isPrintZYD.value = flag;
    }
  } catch (error) {
    //todo
  }
  //#endregion
  getAuthorizeDeptList();
});

let authorizeDeptList: any = reactive([]);
// 获取设计模式表单的选择表达式
function getAuthorizeDeptList() {
  authorizeDeptList.length = 0; //放入数据前清空数据
  const url = '/api/sys/getDepartAuthorizementList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { orgId, username: store.userInfo.username, deptNoList } })
    .then((res: any) => {
      authorizeDeptList.push(...res.data);
    })
    .catch((err: any) => {});
}
/**加载缓存中的科室 */
function loadCacheDeps(depNos) {
  if (!deptDropSelectRef.value) {
    setTimeout(() => {
      loadCacheDeps(depNos);
    }, 200);
    return;
  }
  let arr = [];
  if (!IsEmpty(depNos) && depNos.includes(',')) {
    arr = depNos.split(',');
  } else {
    arr.push(depNos);
  }
  const url = '/api/sys/fingDepartmentNamesByCodes';
  proxy.$http.get(url, { params: { nos: arr } }).then((res: any) => {
    if (res && res.status && res.status.code && res.status.code === 1) {
      deptDropSelectRef.value?.initBaseText(!IsEmpty(res.data) ? res.data : '');
    }
  });
}

/**加载缓存中的来源 */
function loadCachePatType(patTypes) {
  if (!patTypeSelectRef.value) {
    setTimeout(() => {
      loadCachePatType(patTypes);
    }, 200);
    return;
  }
  let arr = [];
  if (!IsEmpty(patTypes) && patTypes.includes(',')) {
    arr = patTypes.split(',');
  } else {
    arr.push(patTypes);
  }
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http.get(url, { params: { code: 'PATTYPE' } }).then((res: any) => {
    if (res && res.status && res.status.code && res.status.code === 1) {
      //判断code是否在数组arr中存在
      const names = res.data.filter((item: any) => arr.includes(item.code));
      patTypeSelectRef.value?.initBaseText(!IsEmpty(names) ? names.map((item: any) => item.name).join(',') : '');
    }
  });
}

//根据字典ID查询报表
function getReportId() {
  const url = '/api/pubReport/getReportByReportCode';
  proxy.$http
    .get(url, { params: { reportCode: '1754032534504218624' } })
    .then((res: any) => {
      reportId = res.data;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

//作废标本
async function cancelSpec() {
  const row = printBarcodeQueryTable.value?.getCurrentRecord();
  if (!row || IsEmpty(row.id)) {
    VxeMessage('请选择要作废的条码', VxeNotifyType.warning);
    return;
  }
  const rowIndex = printBarcodeQueryTable.value?.getRowIndex(row);
  const type = await VXETable.modal.confirm('确定要删除当前选中的数据？');
  if (type === 'confirm') {
    const url = '/lab/reqMain/cancelReqMain';
    proxy.$http
      .get(url, { params: { reqNo: row.reqNo } })
      .then((res: any) => {
        //reportId = res.data;
        if (res && res.status && res.status.code && res.status.code === 1) {
          VxeMessage('作废成功', VxeNotifyType.success);
          printBarcodeQueryList[rowIndex].state = res.data.state;
          printBarcodeQueryList[rowIndex].stateNa = res.data.stateNa;
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
  }
}

// #endregion
function setCurComputerCheckedisPrintZYD() {
  const flag = localStorage.getItem('isPrintZYD');
  if (flag) {
    localStorage.removeItem('isPrintZYD');
    isPrintZYD.value = '0';
    VXETable.modal.message({ content: '取消配置成功', status: 'warning' });
  } else {
    localStorage.setItem('isPrintZYD', '1');
    isPrintZYD.value = '1';
    VXETable.modal.message({ content: '配置成功', status: 'success' });
  }
}

//单元格样式
function cellStyle({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'sameSpecCodeBgColor') {
    return { backgroundColor: row.sameSpecCodeBgColor };
  }
}

//单元格背景颜色
function cellClassName({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'isUrgent' && row.isUrgent) {
    return 'bg-red';
  }
}

function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findPrintBarcodeSpecList();
  }
}

//身份证回车事件
function IDNoValueChangeEnter() {}

//读卡按钮
function IdNoFocus() {}

// 查询申请列表
function findPrintBarcodeSpecList() {
  loading.value = true;
  printBarcodeQueryList.length = 0;
  const url = '/lab/reqMainBak/barcodePrintQueryOrMaininfo';
  const data = {
    patNo: newForm.patNo,
    beforePatNo: newForm.beforePatNo,
    reqNo: newForm.reqNo,
    bedNo: newForm.bedNo,
    patType: newForm.patType,
    deptNo: newForm.deptNo,
    patNa: newForm.patNa,
    IDNo: newForm.IDNo,
    reqDateS: newForm.reqDateS,
    reqDateE: newForm.reqDateE,
    searchValue: newForm.searchValue
  };
  //his调用页面，需要控制授权科室
  if (!IsEmpty(barObjKey.value)) {
    if (data.deptNo.length == 0) {
      if (authorizeDeptList.length > 0) {
        let codes = authorizeDeptList.map((item: any) => item.code);
        data.deptNo = codes;
      } else {
        data.deptNo = ['!@#QWE'];
      }
    }
  }

  proxy.$http
    .post(url, data)
    .then((res: any) => {
      printBarcodeQueryList.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询列表失败', VxeNotifyType.error);
    });
}

//待打印勾选修改,为了勾选一个同医嘱的都勾选和取消
function checkboxStateChange({ checked, row }) {
  const arr = printBarcodeQueryList.filter((e) => {
    return e.reqNo == row.reqNo;
  });
  if (arr && arr.length > 0) {
    const $xTable = proxy.$refs.printBarcodeQueryTable as any;
    arr.forEach((e) => {
      $xTable.setCheckboxRow(e, checked);
    });
  }
}

//待打印行点击
function printBarcodeQueryRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    currentPrintBarcode = {} as any;
    return;
  }
  currentRowIndex = rowIndex;
  currentPrintBarcode = row;
  const xTable = proxy.$refs.printBarcodeQueryTable as any;
  xTable.setCurrentRow(row);

  afterPrintBarcodeSpecList.length = 0;
  afterloading.value = true;
  const url = '/api/reqdetail/getDetailByBarcode';
  proxy.$http
    .get(url, { params: { reqNo: row.reqNo } })
    .then((res: any) => {
      afterPrintBarcodeSpecList.push(...res.data);
      afterloading.value = false;
    })
    .catch((err: any) => {
      afterloading.value = false;
      proxy.$alert(err, '提示');
    });
}

//打印按钮 (准备选中的数据)
function printManyStep1(tableName: any) {
  const $xTable = proxy.$refs[tableName] as any;
  const selectRows = $xTable.getCheckboxRecords();

  if (!(selectRows && selectRows.length > 0 && selectRows[0])) {
    VxeMessage('请先选中要打印的条码', VxeNotifyType.info);
  } else {
    let isPrint = false;
    let printRows = [];
    let reqNos = [];
    selectRows.forEach((row) => {
      if (row.state === '150') {
        isPrint = true;
        reqNos.push(row.reqNo);
        return;
      }
      printRows.push(row);
    });
    if (isPrint) {
      VxeMessage(reqNos.join(',') + ':标本条码已作废,无法重打', VxeNotifyType.info);
    }
    if (printRows.length === 0) {
      return;
    }
    const commaSeparatedIds = printRows.map((row) => row.id);
    const splitArr = splitArray(commaSeparatedIds);
    let paramsArr = [];
    splitArr.forEach((carr, i) => {
      let ids = carr.join(',');
      paramsArr.push({ ReportName: reportId, ReportParameters: [{ Name: 'Id', Value: ids }], PdfPrinterSetting: { PdfPrinterCopies: 1 } });
    });

    let ids = commaSeparatedIds.join(',');

    // 调用报表,发送打印任务
    printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'Id', Value: ids }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };

    //打印导引单
    if (isPrintZYD.value && isPrintZYD.value === '1') {
      printParamsZydObj.value = [{ ReportName: '1768211380161925122', ReportParameters: [], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
    }

    // 清空查询条件
    clearFormConditions();
  }
}

function clearFormConditions() {
  newForm.searchValue = '';
  newForm.patNo = '';
  newForm.beforePatNo = '';
  newForm.reqNo = '';
  newForm.bedNo = '';
  newForm.patType = [];
  newForm.deptNo = [];
  newForm.patNa = '';
  newForm.reqDateS = formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00');
  newForm.reqDateE = formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59');
}

// 组件
//点击选择的那一项受检单位
function SelectRowClick(row) {
  newForm.patTypeName = row.name;
  newForm.patType = row.code;
}

// 清空表单值方法  子组件传递
function clearPatTypeName() {
  newForm.patTypeName = '';
  newForm.patType = '';
}

// 组件选中事件
function selectRow(row, index) {
  deptIds.value = '';
  newForm.deptNo.length = 0;
  const nameArr = [];
  const deptIdArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    newForm.deptNo.push(item.code);
    deptIdArr.push(item.id);
  });

  newForm.deptNa = nameArr.join(',');
  deptIds.value = deptIdArr.join(',');
}

// 病人来源组件选中事件
function selectPatTypeNameRow(row, index) {
  deptIds.value = '';
  newForm.patType.length = 0;
  const nameArr = [];
  const deptIdArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    newForm.patType.push(item.code);
    deptIdArr.push(item.code);
  });

  newForm.patTypeName = nameArr.join(',');
  typeIds.value = deptIdArr.join(',');
}
/**待打印表格右键单机 */
function contextMenuClickEvent({ menu, row, column }) {
  switch (menu.code) {
    case 'copy':
      // 示例
      if (row && column) {
        if (XEClipboard.copy(row[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
      }
      break;
    case 'cancel':
      // 示例
      if (row && column) {
        cancelSpec();
      }
      break;
    default:
    //VXETable.modal.alert(`点击了 ${menu.name} 选项`)
  }
}

function exportExcel(){
  // 获取表格实例
  const table = proxy.$refs.printBarcodeQueryTable;
      // 调用表格的 exportData 方法导出 Excel
      table.exportData('xlsx', {
        fileName: 'table_data', // 导出的文件名
        types: ['header', 'body'] // 导出的数据类型，包含表头和表体
      }).then(() => {
        console.log('导出成功')
      }).catch((err) => {
        console.error('导出失败', err)
      })
}


</script>

<style lang="scss" scoped>
#printBarcodeQuery {
  height: 100%;
  width: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;
    }
  }

  .printBarcodeQueryTable {
    height: calc(100vh - 160px);
  }
}

.custom-checkbox {
  font-size: 16px;
  cursor: pointer;
}
</style>
